package com.thingsgrid.mqtthelper.config;

import com.thingsgrid.mqtthelper.service.MqttReceiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * 功能说明：MQTT消费者
 *
 * @author 李龙飞
 * @since 2019/8/26 14:54
 */

@Configuration
public class MqttConsumer {

    @Value("${spring.mqtt.client.id}")
    private String clientId;

    @Value("${spring.mqtt.default.topic}")
    private String defaultTopic;

    //消息处理service
	@Autowired
    private MqttReceiveService mqttReceiveService;

    @Autowired
    private MqttConnection mqttConnection;


    @Bean
    public MessageChannel mqttInputChannel(){
        return new DirectChannel();
    }

    //配置client,监听的topic
    @Bean
    public MessageProducer inbound() {
        MqttPahoMessageDrivenChannelAdapter adapter =MqttAdapterConfig.getInstanceAdapter(clientId+"_inbound", mqttConnection.mqttClientFactory()) ;
        String[] topics = defaultTopic.split(",");
        for(String topic:topics){
            System.out.println(topic);
            if(!StringUtils.isEmpty(topic)){
                adapter.addTopic(topic,1);
            }
        }

        adapter.setCompletionTimeout(3000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    //通过通道获取数据
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return new MessageHandler() {
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                String topic = Objects.requireNonNull(message.getHeaders().get("mqtt_receivedTopic")).toString();
                mqttReceiveService.handlerMqttMessage(topic,message.getPayload().toString());
            }
        };
    }
}
